#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
依赖安装脚本 - 为代码提取器安装必要的依赖
"""

import subprocess
import sys
import tkinter as tk
from tkinter import messagebox

def check_python_version():
    """检查Python版本是否满足要求"""
    if sys.version_info < (3, 6):
        print("错误: 需要Python 3.6或更高版本")
        return False
    return True

def check_tkinter():
    """检查tkinter是否可用"""
    try:
        import tkinter
        return True
    except ImportError:
        return False

def install_package(package):
    """安装指定的包"""
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        return True
    except subprocess.CalledProcessError:
        return False

def main():
    """主函数"""
    if not check_python_version():
        print("请升级您的Python版本")
        return
    
    # 创建简单的GUI
    root = tk.Tk()
    root.title("代码提取器 - 依赖安装")
    root.geometry("500x300")
    
    frame = tk.Frame(root, padx=20, pady=20)
    frame.pack(fill=tk.BOTH, expand=True)
    
    tk.Label(frame, text="代码提取器 - 依赖安装", font=("Arial", 14, "bold")).pack(pady=10)
    
    # 检查tkinter
    tk_status = "已安装" if check_tkinter() else "未安装"
    tk.Label(frame, text=f"tkinter: {tk_status}", anchor="w").pack(fill=tk.X, pady=5)
    
    # 检查python-docx
    try:
        import docx
        docx_status = "已安装"
    except ImportError:
        docx_status = "未安装"
    
    tk.Label(frame, text=f"python-docx: {docx_status}", anchor="w").pack(fill=tk.X, pady=5)
    
    # 安装按钮
    def install_docx():
        label_status.config(text="正在安装python-docx...")
        root.update()
        
        if install_package("python-docx"):
            label_status.config(text="python-docx安装成功！")
            button_install.config(state=tk.DISABLED)
        else:
            label_status.config(text="安装失败，请尝试手动安装: pip install python-docx")
    
    button_install = tk.Button(frame, text="安装python-docx", command=install_docx)
    button_install.pack(pady=10)
    
    if docx_status == "已安装":
        button_install.config(state=tk.DISABLED)
    
    label_status = tk.Label(frame, text="", anchor="w")
    label_status.pack(fill=tk.X, pady=5)
    
    # 启动代码提取器按钮
    def start_extractor():
        try:
            import subprocess
            subprocess.Popen([sys.executable, "code_extractor.py"])
            root.destroy()
        except Exception as e:
            messagebox.showerror("错误", f"启动代码提取器失败: {str(e)}")
    
    tk.Button(frame, text="启动代码提取器", command=start_extractor).pack(pady=10)
    
    # 退出按钮
    tk.Button(frame, text="退出", command=root.destroy).pack(pady=5)
    
    # 状态信息
    if not check_tkinter():
        label_status.config(text="警告: tkinter未安装，代码提取器无法运行。请安装tkinter库。")
    
    root.mainloop()

if __name__ == "__main__":
    main() 